import tensorflow as tf
import warnings
import  numpy as np
warnings.filterwarnings('ignore')
# m1 = tf.constant([[3,3]])
# m2 = tf.constant([[2],[3]])
#
# res = tf.matmul(m1,m2)
#
# # 定义一个会话，一层层上运行，类似于main（）
# sess = tf.Session()
# result = sess.run(res)
# print(result)
# sess.close()
# # 此种 无需关闭
# with tf.Session() as sess:
#     result = sess.run(res)
#     print(result)
#
#
# # —————变量的使用———————————————
# x = tf.Variable([1,2])
# a = m1
# sub = tf.subtract(x,a)
# add = tf.add(x,sub)
# init = tf.global_variables_initializer()
# with tf.Session() as sess:
#     sess.run(init)
#     print(sess.run(sub))
#     print(sess.run(add))
#
# state = tf.Variable(0,name='counter')
# # 作用是 使得state加1
# new_vaule = tf.add(state,1)
# # 赋值op
# update = tf.assign(state,new_vaule)
# init = tf.global_variables_initializer()
# with tf.Session( ) as sess:
#     sess.run(init)
#     print(sess.run(state))
#     for _ in range(5):
#         sess.run(update)
#         print(sess.run(state))

# ------fetch- 同时运行-------------------------------
# input1 = tf.constant(3.0)
# input2 = tf.constant(2.0)
# input3 = tf.constant(5.0)
#
# add = tf.add(input2,input3)
# mul = tf.multiply(input1,add)
# with tf.Session() as sess:
#     result = sess.run([mul,add])
#     print(result)
#
# # Feed 创建占位符
# input4 = tf.placeholder(tf.float32)
# input5 = tf.placeholder(tf.float32)
# output = tf.multiply(input4,input5)
# with tf.Session() as sess:
#     # feed 的数据以字典形式传入
#     print(sess.run(output,feed_dict={input4:[7.0],input5:[2.0]}))

# -实例  使用梯度下降法，拟合一次模型曲线-------------------------------
x_data = np.random.rand(100)
y_data = x_data*0.1+0.2

b = tf.Variable(80.)
k = tf.Variable(10.)
y = k*x_data +b
# 二次代价函数
loss = tf.reduce_mean(tf.square(y_data-y))#真实值减去预测值
# 梯度下降的训练优化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5)
# 最小化代价函数
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for step in range(1000):
        sess.run(train)
        if step%20 ==0:
            print(step,sess.run([k,b]))
